<template>
  <!-- 添加或修改专家对话框 -->
  <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="visible" width="800px" append-to-body @close="cancel">
    <el-form ref="bizExpertRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="姓名" prop="name">
        <el-input maxlength="50" class="input-width" v-model="form.name" placeholder="请输入姓名"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input maxlength="50" v-model="form.phone" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input maxlength="50" v-model="form.email" placeholder="请输入邮箱"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="ExpertAdd">
import {addBizExpert, getBizExpert, updateBizExpert} from "@/api/biz/bizExpert";

const {proxy} = getCurrentInstance();
const emit = defineEmits(["ok"]);
const props = defineProps({
  id: {
    type: [Number, String]
  }
});
watch(() => props.id, (newId) => {
  dataId.value = newId;
});

const visible = ref(false);
const title = ref("");
const dataId = ref(null);
const data = reactive({
  form: {},
  rules: {
    name: [
      {required: true, message: "姓名不能为空", trigger: "submit"}
    ],
    phone: [
      {required: true, message: "手机号不能为空", trigger: "submit"},
      { pattern: /^[1][3-9][0-9]{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
  }
});
const {form, rules} = toRefs(data);
// 表单重置
function reset() {
  form.value = {
    id: null,
    createTime: null,
    updateTime: null,
    deleted: null,
    name: null,
    phone: null,
    email: null,
    userId: null
  };
  proxy.resetForm("bizExpertRef");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bizExpertRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBizExpert(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          visible.value = false;
          emit("ok");
        });
      } else {
        addBizExpert(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          visible.value = false;
          emit("ok");
        });
      }
    }
  });
}

function cancel() {
  visible.value = false;
}

// 显示弹框
function show() {
  visible.value = true;
  reset();
  if(dataId.value){
    getBizExpert(dataId.value).then(response => {
      form.value = response.data;
      title.value = "修改专家";
    });
  }else{
    title.value = "添加专家";
  }
}
defineExpose({
  show,
});
</script>